﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Android;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Support.V4.Widget;
using Android.Support.V4;
using Android.Views;
using Android.Widget;
using Engine.Media;
using pakdll;
using SCPAK;
using System.Threading;
using Android.Support.V4.Content;

namespace SCPAK2
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true, LaunchMode = LaunchMode.SingleTask)]
    public class MainActivity : Activity
    {
        public string lastSubPath;
        public FileListAdapter FileListAdapter;
        public FileListAdapter fileSubListAdapter;
        public int ActiveWindow = 1;
        public ListView fileList;
        public ListView fileSubList;
        public bool IsBackPressed = false;
        public string lastPath = "";
        public TimerCallback timerCallback;
        public MyDialog my;
        public static string rootPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
        public SwipeRefreshLayout listre, sublistre;
        public Handler handler;
        public Timer Timer;
        public TextView listnone, sublistnone;
        public bool IsInPak = false;
        public bool IsSubInPak = false;
        public string InPakPath = string.Empty;
        public string InSubPakPath = string.Empty;
        private SelectOptionDialog SelectOptionDialog;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            bool flag = false;
            if (ContextCompat.CheckSelfPermission(this,Manifest.Permission.WriteExternalStorage) != Permission.Granted)
            {//请求权限
                RequestPermissions(new string[] { Manifest.Permission.WriteExternalStorage, Manifest.Permission.ReadExternalStorage }, 0);
            }
            else
            {
                flag = true;
            }
            SetContentView(Resource.Layout.activity_main);
            timerCallback = new TimerCallback(Tick);
            FileListAdapter = new FileListAdapter(this);
            fileSubListAdapter = new FileListAdapter(this);
            SelectOptionDialog = new SelectOptionDialog(this);
            fileList = FindViewById<ListView>(Resource.Id.fileList);
            fileSubList = FindViewById<ListView>(Resource.Id.fileSubList);
            listre = FindViewById<SwipeRefreshLayout>(Resource.Id.listrefresh);
            sublistre = FindViewById<SwipeRefreshLayout>(Resource.Id.sublistrefresh);
            sublistnone = FindViewById<TextView>(Resource.Id.sublistnone);
            listnone = FindViewById<TextView>(Resource.Id.listnone);
            sublistre.Refresh += (a, b) =>
            {
                ActiveWindow = 2;
                RefreshFileList(lastSubPath, fileSubListAdapter);
                sublistre.Refreshing = false;
            };
            listre.Refresh += (a, b) =>
            {
                ActiveWindow = 1;
                RefreshFileList(lastPath, FileListAdapter);
                listre.Refreshing = false;
            };
            fileList.Tag = 1;
            fileList.ItemLongClick += new EventHandler<AdapterView.ItemLongClickEventArgs>(LongClick);
            fileList.ItemClick += new EventHandler<AdapterView.ItemClickEventArgs>(Onclick);
            fileList.Adapter = FileListAdapter;
            fileSubList.Adapter = fileSubListAdapter;
            fileSubList.Tag = 2;
            fileSubList.ItemLongClick += new EventHandler<AdapterView.ItemLongClickEventArgs>(LongClick);
            fileSubList.ItemClick += new EventHandler<AdapterView.ItemClickEventArgs>(Onclick);            
            my = new MyDialog(this);
            handler = new Handler(handleMessage);
            if (flag)
            {
                RefreshFileList(rootPath, FileListAdapter);
                RefreshFileList(rootPath, fileSubListAdapter);
            }
        }

        public void Tick(object state)
        {
            IsBackPressed = false;
            Timer.Dispose();
        }
        public override bool OnCreateOptionsMenu(IMenu menu)
        {
            menu.Add("新建文件夹");
            menu.Add("QQ下载");
            menu.Add("退出");
            return base.OnCreateOptionsMenu(menu);
        }
        public override bool OnMenuItemSelected(int featureId, IMenuItem item)
        {
            switch (item.ToString())
            {
                case "新建文件夹": {
                        my.SetEditText("提示", "请输入文件夹名称", string.Empty,(text) => {
                            try
                            {
                                Directory.CreateDirectory(Path.Combine(ActiveWindow == 1 ? lastPath : lastSubPath, text));
                                tip("创建成功");
                                sendRefreshFileList();
                                my.Dismiss();
                            }
                            catch
                            {
                                tip("失败，无效的名称");
                            }
                        });
                        my.Show();
                        break;
                    }
                case "QQ下载":
                    {
                        ToQQFileRev();
                        break;
                    }
                case "退出":
                    {
                        System.Environment.Exit(0);
                        break;
                    }
                default:
                    {
                        break;
                    }
            }
            return true;
        }
        public void refreshClick(object obj, EventArgs arg)
        {
            RefreshFileList(lastPath, FileListAdapter);
            RefreshFileList(lastSubPath, fileSubListAdapter);
        }
        public void LongClick(object obj, AdapterView.ItemLongClickEventArgs arg)
        {
            ListView listView = (ListView)obj;
            int d = (int)listView.Tag;
            ActiveWindow = d;
            int pos = arg.Position;
            SelectOptionDialog.Clear();
            FileItem item;
            if (d == 1)
            {
                item = FileListAdapter.GetItem2(pos);
            }
            else
            {
                item = fileSubListAdapter.GetItem2(pos);
            }
            SelectOptionDialog.setText("请选择操作["+item.FileName+"]");
            switch (item.Type)
            {
                case FileItemType.Storage:
                    {                        
                        DirectoryInfo directory = null;
                        FileInfo file = null;
                        if (item.IsDir) directory = new DirectoryInfo(item.AbsolutePath);
                        else file = new FileInfo(item.AbsolutePath);
                        SelectOptionDialog.Add("打包为2.1版Pak", delegate
                        {
                            sendDialogHiden();
                            sendDialog("提示", "目标版本:2.1\n打包中...");
                            sendDialogCancelable(false);
                            try
                            {
                                new Pak21(directory.FullName, this);
                                sendDialog("提示", "打包成功");
                                sendDialogCancelable(true);
                                sendRefreshFileList();
                            }
                            catch (System.Exception e)
                            {
                                sendDialogCancelable(true);
                                sendDialog("打包出错", e.ToString());
                            }
                        });
                        SelectOptionDialog.Add("打包为2.2版Pak", delegate
                        {
                            sendDialogHiden();
                            sendDialog("提示", "目标版本:2.2\n打包中...");
                            sendDialogCancelable(false);
                            try
                            {
                                new Pak(directory.FullName,2, this);
                                sendDialogCancelable(true);
                                sendDialog("提示", "打包成功");
                                sendRefreshFileList();
                            }
                            catch (System.Exception e)
                            {
                                sendDialogCancelable(true);
                                sendDialog("打包出错", e.ToString());
                            }

                        });
                        SelectOptionDialog.Add("打包为2.3版Pak", delegate
                        {
                            sendDialogHiden();
                            sendDialog("提示", "目标版本:2.3\n打包中...");
                            sendDialogCancelable(false);
                            try
                            {
                                new Pak(directory.FullName, 3, this);
                                sendDialogCancelable(true);
                                sendDialog("提示", "打包成功");
                                sendRefreshFileList();
                            }
                            catch (System.Exception e)
                            {
                                sendDialogCancelable(true);
                                sendDialog("打包出错", e.ToString());
                            }

                        });
                        SelectOptionDialog.Add("删除此项", delegate
                        {
                            sendDialogHiden();
                            sendDialogCancelable(false);
                            if (file != null)
                            {
                                sendDialog("提示", "删除中文件" + file.Name + "...");
                            }
                            else
                            {
                                sendDialog("提示", "删除目录中" + directory.Name + "...");
                            }

                            if (file != null)
                            {
                                file.Delete();
                            }
                            else
                            {
                                directory.Delete(true);
                            }

                            sendDialog("提示", "删除成功");
                            sendDialogCancelable(true);
                            sendRefreshFileList();
                        });
                        if (file != null)
                        {
                            SelectOptionDialog.Add("移动文件到" + (d == 1 ? "右" : "左") + "边", delegate
                            {
                                sendDialogHiden();
                                try
                                {
                                    if (d == 1)
                                    {
                                        file.MoveTo(Path.Combine(lastSubPath, file.Name));
                                    }
                                    else
                                    {
                                        file.MoveTo(Path.Combine(lastPath, file.Name));
                                    }

                                    sendDialog("提示", "移动成功");
                                    sendRefreshFileList();
                                }
                                catch (System.Exception edd)
                                {
                                    sendDialog("提示", "移动失败:" + edd.Message);
                                }
                            });
                            SelectOptionDialog.Add("复制文件到" + (d == 1 ? "右" : "左") + "边", delegate
                            {
                                sendDialogHiden();
                                try
                                {
                                    if (d == 1)
                                    {
                                        file.CopyTo(Path.Combine(lastSubPath, file.Name), true);
                                    }
                                    else
                                    {
                                        file.CopyTo(Path.Combine(lastPath, file.Name), true);
                                    }

                                    sendDialog("提示", "复制成功");
                                    sendRefreshFileList();
                                }
                                catch (System.Exception edd)
                                {
                                    sendDialog("提示", "复制失败:" + edd.Message);
                                }
                            });
                            if (file.Extension == ".png")
                            {
                                try
                                {
                                    Image image = Png.Load(file.Open(FileMode.Open));
                                    SelectOptionDialog.Add("转换到32位Png", delegate
                                    {
                                        sendDialogHiden();
                                        sendDialog("提示", "转换图片中...");
                                        sendDialogCancelable(false);
                                        savepng(image, file);
                                        sendDialog("提示", "转换成功");
                                        sendDialogCancelable(true);
                                        sendRefreshFileList();
                                    });
                                }
                                catch
                                {

                                }
                            }
                            else if (file.Extension == ".jpg" || file.Extension == ".jpeg")
                            {
                                try
                                {
                                    Image image = Jpg.Load(file.Open(FileMode.Open));
                                    SelectOptionDialog.Add("转换到32位Png", delegate
                                    {
                                        sendDialogCancelable(false);
                                        sendDialog("提示", "转换图片中...");
                                        savepng(image, file);
                                        sendDialog("提示", "转换成功");
                                        sendDialogCancelable(true);
                                        sendRefreshFileList();
                                    });
                                }
                                catch { }
                            }
                            else if (file.Extension == ".dll" || file.Extension == ".exe")
                            {
                                SelectOptionDialog.Add("尝试加载这个dll", delegate
                                {
                                    sendDialogHiden();
                                    loadDll(file);
                                });
                            }
                        }
                        SelectOptionDialog.Add("打包为scmod", delegate
                        {
                            sendDialogHiden();
                            sendDialogCancelable(false);
                            makezip(item, "scmod");
                            sendDialogCancelable(true);
                            sendRefreshFileList();
                        });
                        SelectOptionDialog.Add("打包为zip", delegate
                        {
                            sendDialogHiden();
                            sendDialogCancelable(false);
                            makezip(item, "zip");
                            sendDialogCancelable(true);
                        });
                        SelectOptionDialog.Add("查看已加载的dll", delegate
                        {
                            sendDialogHiden();
                            sendShowdlls();
                        });                        
                        break;
                    }
                case FileItemType.Zip:
                    {
                        SelectOptionDialog.Add("解压全部到" + (ActiveWindow == 1 ? "右" : "左") + "边", delegate {
                            new Thread(new ThreadStart(delegate {
                                SendTipDialog("解压中" + item.FileName + "..");
                                sendDialogCancelable(false);
                                using (Stream stream = File.OpenRead(ActiveWindow == 1 ? lastPath : lastSubPath))
                                {
                                    ExtractZip(ZipArchive.Open(stream), string.Empty, ActiveWindow == 1 ? lastSubPath : lastPath, true);
                                }
                                sendRefreshFileList(ActiveWindow == 1 ? 2 : 1);
                                sendDialogHiden();
                                SendTipDialog("解压成功");
                                sendDialogCancelable(true);
                            })).Start();
                        });
                        SelectOptionDialog.Add("解压选中到" + (ActiveWindow == 1 ? "右" : "左") + "边",delegate {
                            new Thread(new ThreadStart(delegate {
                                SendTipDialog("解压中" + item.FileName + "..");
                                sendDialogCancelable(false);
                                using (Stream stream = File.OpenRead(ActiveWindow == 1 ? lastPath : lastSubPath)) {
                                    ExtractZip(ZipArchive.Open(stream),item.IsDir ? Path.GetDirectoryName(item.AbsolutePath): item.AbsolutePath, ActiveWindow == 1 ? lastSubPath : lastPath, item.IsDir);
                                }
                                sendRefreshFileList(ActiveWindow == 1 ? 2 : 1);
                                sendDialogHiden();
                                SendTipDialog("解压成功");
                                sendDialogCancelable(true);
                            })).Start();
                        });
                        break;
                    }
                case FileItemType.Pak:
                    {
                        SelectOptionDialog.Add("解压全部到" + (ActiveWindow == 1 ? "右" : "左") + "边", delegate {
                            new Thread(new ThreadStart(delegate {
                                SendTipDialog("读取中" + item.FileName + "..");
                                sendDialogCancelable(false);
                                int ver = readPakVersion(ActiveWindow == 1 ? lastPath : lastSubPath);
                                if (ver == 1)
                                {
                                    List<PakInfo> infos = UnPak21.ReadPakInfo(ActiveWindow == 1 ? lastPath : lastSubPath, (fname) => {
                                        return true;
                                    });
                                    UnPakData._UnPakData(infos, ActiveWindow == 1 ? lastSubPath : lastPath, this);
                                }
                                else
                                {
                                    List<PakInfo> infos = UnPak.ReadPakList(ActiveWindow == 1 ? lastPath : lastSubPath, ver == 2 ? UnPak.Pad22() : UnPak.Pad23(), (name) => { return true; });
                                    UnPak.Load(infos, ver, ActiveWindow == 1 ? lastSubPath : lastPath, this);
                                }
                                sendRefreshFileList(ActiveWindow == 1 ? 2 : 1);
                                sendDialogHiden();
                                SendTipDialog("解压成功");
                                sendDialogCancelable(true);
                            })).Start();
                        });

                        SelectOptionDialog.Add("解压选中到" + (ActiveWindow == 1 ? "右" : "左") + "边", delegate {
                            new Thread(new ThreadStart(delegate {
                                SendTipDialog("读取中" + item.FileName + "..");
                                sendDialogCancelable(false);
                                int ver = readPakVersion(ActiveWindow == 1 ? lastPath : lastSubPath);
                                if (ver == 1)
                                {
                                    List<PakInfo> infos = UnPak21.ReadPakInfo(ActiveWindow == 1 ? lastPath : lastSubPath, (fname) => {
                                        if (item.IsDir) return fname.StartsWith(item.FileName); else return fname == item.AbsolutePath;
                                    });
                                    UnPakData._UnPakData(infos, ActiveWindow == 1 ? lastSubPath : lastPath, this);
                                }else {
                                    List<PakInfo> infos = UnPak.ReadPakList(ActiveWindow == 1 ? lastPath : lastSubPath, ver == 2 ? UnPak.Pad22() : UnPak.Pad23(), (fname) => {
                                        if (item.IsDir) return fname.StartsWith(item.FileName); else return fname == item.AbsolutePath;
                                    });
                                    try
                                    {
                                        UnPak.Load(infos, ver, ActiveWindow == 1 ? lastSubPath : lastPath, this);
                                    }
                                    catch (Exception e)
                                    {
                                        SendTipDialog("解压出错：" + e.Message);
                                    }
                                }
                                sendRefreshFileList(ActiveWindow == 1 ? 2 : 1);
                                sendDialogHiden();
                                SendTipDialog("解压成功");
                                sendDialogCancelable(true);
                            })).Start();
                        });
                        break;
                        break;

                    }
            }
            SelectOptionDialog.Show();
        }
        public void listDlls()
        {
            SelectOptionDialog.Clear();
            SelectOptionDialog.SetTitle("已加载的dll");
            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                string name = assembly.GetName().Name;
                if (!name.StartsWith("Xamarin"))
                {
                    SelectOptionDialog.Add(name + "[" + assembly.GetName().Version + "]", delegate
                    {
                        MethodInfo methodInfo = assembly.EntryPoint;
                        if (methodInfo != null)
                        {
                            try
                            {
                                methodInfo.Invoke(null, null);
                            }
                            catch (System.Exception ex)
                            {
                                sendDialog("执行入口方法" + methodInfo.Name + "失败", ex.Message);
                            }
                        }
                        else
                        {
                            SendTipDialog("该程序集不存在入口");
                        }
                    });
                }
            }
            SelectOptionDialog.Show();
        }
        public void savepng(Image from, FileInfo file)
        {
            Image.Save(from, File.Create(Path.Combine(file.Directory.FullName, file.Name.Split(new string[] { file.Extension }, StringSplitOptions.RemoveEmptyEntries)[0] + "1" + file.Extension)), ImageFileFormat.Png, true);
        }
        public void makezip(FileItem obj, string type)
        {
            sendDialog("提示", "打包中...目标:" + type);
            try
            {

                if (obj.IsDir)
                {
                    ZipArchive zipArchive = ZipArchive.Create(File.Create(Path.Combine(obj.AbsolutePath + "." + type)));
                    AddZip(new DirectoryInfo(obj.AbsolutePath), zipArchive, obj.AbsolutePath);
                    zipArchive.Close();
                }
                else
                {
                    ZipArchive zipArchive = ZipArchive.Create(File.Create(Path.Combine(Path.GetDirectoryName(obj.AbsolutePath), obj.FileNameWithoutExtension + "." + type)));
                    using (Stream stream = File.OpenRead(obj.AbsolutePath))
                    {
                        zipArchive.AddStream(obj.FileName, stream);
                    }
                    zipArchive.Close();
                }
                sendDialog("提示", "打包完成");
                sendRefreshFileList();
            }
            catch (System.Exception e)
            {
                sendDialog("打包出错", e.ToString());
            }
        }
        /// <summary>
        /// 压缩文件夹
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="zip"></param>
        /// <param name="needDel">分割相对路径</param>
        public void AddZip(DirectoryInfo dir, ZipArchive zip, string needDel)
        {
            foreach (DirectoryInfo directory in dir.GetDirectories())
            {
                AddZip(directory, zip, needDel);
            }
            foreach (FileInfo file in dir.GetFiles())
            {
                zip.AddStream(file.FullName.Split(new string[] { needDel }, StringSplitOptions.RemoveEmptyEntries)[0], file.OpenRead());
            }
        }
        public void handleMessage(Message msg)
        {
            switch (msg.What)
            {
                case 0:
                    bool dp = (bool)msg.Obj;
                    my.SetCancelable(dp);
                    break;
                case 1:
                    string[] tmp = (string[])msg.Obj;
                    my.setText(tmp[0], tmp[1]);
                    if (!my.IsShowing)
                    {
                        my.Show();
                    }

                    break;
                case 2:
                    {
                        my.setText("Loading","读取中");
                        my.Show();
                        int type = (int)msg.Obj;
                        if (type == 0) type = ActiveWindow;
                        if(type==1) RefreshFileList(lastPath, FileListAdapter);
                        else RefreshFileList(lastSubPath, fileSubListAdapter);
                        my.Dismiss();
                        break;                        
                    }
                case 3: SelectOptionDialog.Hide(); break;
                case 4: listDlls(); break;
            }
        }
        public void sendShowdlls()
        {
            Message message = new Message();
            message.What = 4;
            handler.SendMessage(message);
        }
        public void sendDialogCancelable(bool flag)
        {
            Message message = new Message();
            message.What = 0;
            message.Obj = flag;
            handler.SendMessage(message);
        }
        public void sendDialog(string t, string m)
        {
            Message message = new Message();
            message.What = 1;
            message.Obj = new string[] { t, m };
            handler.SendMessage(message);
        }
        public void SendTipDialog(string content)
        {
            sendDialog("提示", content);
        }
        public void sendRefreshFileList(int type=0)
        {
            Message message = new Message();
            message.What = 2;
            message.Obj = type;
            handler.SendMessage(message);
        }
        public void sendDialogHiden()
        {
            Message message = new Message();
            message.What = 3;
            handler.SendMessage(message);
        }
        public void ToQQFileRev()
        {
            string path = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, "Android/data/com.tencent.mobileqq/Tencent/QQfile_recv");
            RefreshFileList(path, ActiveWindow == 1 ? FileListAdapter : fileSubListAdapter);
        }
        public bool GetParentPath(string p, out string result)
        {
            if (p == null) { result = rootPath; return false; }
            result = Path.GetFullPath(@"../", p);
            try
            {
                DirectoryInfo info = new DirectoryInfo(result);
                info.GetDirectories();
                return true;
            }
            catch
            {
                return false;
            }
        }
        public void GoToParentDir()
        {
            if (ActiveWindow == 1)
            {
                if (GetParentPath(lastPath, out string result))
                {
                    RefreshFileList(result, FileListAdapter);
                }
            }
            else
            {
                if (GetParentPath(lastSubPath, out string result))
                {
                    RefreshFileList(result, fileSubListAdapter);
                }
            }
        }
        public void RefreshFileList(string path, FileListAdapter obj)
        {
            if (path == null) path = rootPath;
            List<FileItem> fileItems = new List<FileItem>();
            List<FileItem> dirItems = new List<FileItem>();
            string[] dirs = null;
            string[] files = null;
            bool flag = false;
            obj.Clear();

            if ((obj == FileListAdapter && IsInPak) || (obj == fileSubListAdapter && IsSubInPak))
            {
                if (path.EndsWith("zip"))
                {
                    using (Stream stream = File.OpenRead(path))
                    {
                        ZipArchive zipArchive = ZipArchive.Open(stream);
                        List<ZipArchiveEntry> entries = zipArchive.ReadCentralDir();
                        foreach (ZipArchiveEntry entry in entries)
                        {
                            string[] dirlist = null;
                            string relativepath = null;
                            if (ActiveWindow == 1)
                            {
                                if (InPakPath != string.Empty)
                                {
                                    if (entry.FilenameInZip.StartsWith(InPakPath))
                                    {
                                        relativepath = InPakPath + "/";
                                        dirlist = entry.FilenameInZip.Split(relativepath);
                                    }
                                    else continue;
                                }

                            }
                            if (ActiveWindow == 2)
                            {
                                if (InSubPakPath != string.Empty)
                                {
                                    if (entry.FilenameInZip.StartsWith(InSubPakPath))
                                    {
                                        relativepath = InSubPakPath + "/";
                                        dirlist = entry.FilenameInZip.Split(relativepath);
                                    }
                                    else continue;
                                }

                            }
                            string[] nextName = null;
                            if (dirlist == null) { relativepath = "/"; nextName = entry.FilenameInZip.Split("/"); }
                            else nextName = dirlist[1].Split("/");
                            if (nextName.Length == 2)
                            { //目录
                                string name = Path.GetRelativePath(relativepath, Path.GetDirectoryName(entry.FilenameInZip));
                                if (dirItems.Find(px => px.FileName == name) == null) dirItems.Add(new FileItem() { FileName = name, AbsolutePath = entry.FilenameInZip, Type = FileItemType.Zip, IsDir = true });
                            }
                            else if (nextName.Length == 1)
                            {//文件
                                fileItems.Add(new FileItem() { FileNameWithoutExtension = Path.GetFileNameWithoutExtension(entry.FilenameInZip), FileName = Path.GetFileName(entry.FilenameInZip), AbsolutePath = entry.FilenameInZip, Type = FileItemType.Zip, Extension = Path.GetExtension(entry.FilenameInZip) });
                            }
                        }
                        dirItems.Sort();
                        fileItems.Sort();
                    }
                }
                if (path.EndsWith(".pak"))
                {
                    int ver = readPakVersion(path);
                    List<PakInfo> contentlists = new List<PakInfo>();
                    if (ver == 1)
                    {
                        //2.1
                        contentlists = UnPak21.ReadPakInfo(path);
                    }
                    //2.2或2.3
                    else contentlists = UnPak.ReadPakList(path, ver == 2 ? UnPak.Pad22() : UnPak.Pad23());
                    foreach (PakInfo pakInfo in contentlists)
                    {
                        string[] dirlist = null;
                        string relativepath = null;
                        if (ActiveWindow == 1)
                        {
                            if (InPakPath != string.Empty)
                            {
                                if (pakInfo.fileName.StartsWith(InPakPath))
                                {
                                    relativepath = InPakPath + "/";
                                    dirlist = pakInfo.fileName.Split(relativepath);
                                }
                                else continue;
                            }

                        }
                        if (ActiveWindow == 2)
                        {
                            if (InSubPakPath != string.Empty)
                            {
                                if (pakInfo.fileName.StartsWith(InSubPakPath))
                                {
                                    relativepath = InSubPakPath + "/";
                                    dirlist = pakInfo.fileName.Split(relativepath);
                                }
                                else continue;

                            }
                        }
                        string[] nextName = null;
                        if (dirlist == null) { relativepath = "/"; nextName = pakInfo.fileName.Split("/"); }
                        else nextName = dirlist[1].Split("/");
                        if (nextName.Length == 2)
                        { //目录
                            string name = Path.GetRelativePath(relativepath, Path.GetDirectoryName(pakInfo.fileName));
                            if (dirItems.Find(px => px.FileName == name) == null) dirItems.Add(new FileItem() { FileName = name, AbsolutePath = pakInfo.fileName, Type = FileItemType.Pak, IsDir = true });
                        }
                        else if (nextName.Length == 1)
                        {//文件
                            fileItems.Add(new FileItem() { FileNameWithoutExtension = Path.GetFileNameWithoutExtension(pakInfo.fileName), FileName = Path.GetFileName(pakInfo.fileName) + UnPak.GetExtension(pakInfo.typeName), AbsolutePath = pakInfo.fileName, Type = FileItemType.Pak, Extension = UnPak.GetExtension(pakInfo.typeName) });
                        }
                    }
                    dirItems.Sort();
                    fileItems.Sort();
                }
            }
            else
            {
                if (ActiveWindow == 1)
                {
                    lastPath = path;
                }
                else
                {
                    lastSubPath = path;
                }
                try
                {
                    dirs = Directory.GetDirectories(path);
                    files = Directory.GetFiles(path);
                }
                catch (Exception e)
                {
                    flag = true;
                    SendTipDialog("没有访问" + path + "的权限\n" + e.Message);
                }
                if (flag) return;
                foreach (string mm in dirs)
                {
                    string dname = Path.GetRelativePath(path, mm);
                    if (dname.StartsWith("."))
                    {
                        continue;
                    }
                    DirectoryInfo ddd = new DirectoryInfo(mm);
                    if (ddd.Exists)
                    {
                        dirItems.Add(new FileItem() { FileName =dname, AbsolutePath = mm, Type = FileItemType.Storage, IsDir = true });
                        //dirlist.Add(ddd);
                    }
                }
                foreach (string dd in files)
                {
                    string dname = Path.GetFileName(dd);
                    if (dname.StartsWith("."))
                    {
                        continue;
                    }

                    FileInfo fileInfo = new FileInfo(dd);
                    if (fileInfo.Exists)
                    {
                        fileItems.Add(new FileItem() { FileNameWithoutExtension = Path.GetFileNameWithoutExtension(dd), FileName = Path.GetFileName(dd), AbsolutePath = dd, Type = FileItemType.Storage, Extension = Path.GetExtension(dd) });
                        //filelist.Add(fileInfo);
                    }
                }
            }
            fileItems.Sort();
            dirItems.Sort();
            obj.Add(dirItems);
            obj.Add(fileItems);
            if (ActiveWindow == 2)
            {
                if (fileItems.Count+dirItems.Count == 0) sublistnone.Visibility = ViewStates.Visible; else sublistnone.Visibility = ViewStates.Invisible;
            }
            if (ActiveWindow == 1)
            {
                if (fileItems.Count+dirItems.Count == 0) listnone.Visibility = ViewStates.Visible; else listnone.Visibility = ViewStates.Invisible;
            }
            obj.NotifyDataSetChanged();
        }
        public void tip(string txt)
        {
            Toast.MakeText(this, txt, ToastLength.Long).Show();
        }
        private Dictionary<string, int> verMaps = new Dictionary<string, int>();
        private int readPakVersion(string fullname)
        {
            if (!verMaps.TryGetValue(fullname, out int value))
            {
                FileStream fileStream = File.OpenRead(fullname);
                byte[] by = new byte[4];
                int len = fileStream.Read(by, 0, 4);
                fileStream.Close();
                if (len != 4)
                {
                    value = -1;
                }
                else if (by[0] == 0x50 && by[1] == 0x4b && by[2] == 0x32 && by[3] == 0x00)
                {
                    UnPak.ReadPakList(fullname, out int v);
                    if (v == 22) value = 2;
                    else if (v == 23) value = 3;
                    else value = -1;
                }
                else if (by[0] == 0x50 && by[1] == 0x41 && by[2] == 0x4b && by[3] == 0x00)
                {
                    value = 1;
                }
                else
                {
                    value = - 1;
                }
                verMaps.Add(fullname, value);
            }
            return value;
        }
        public void Onclick(object obj, AdapterView.ItemClickEventArgs args)
        {
            int pos = args.Position;
            FileItem item;
            ListView listView = (ListView)obj;
            int d = (int)listView.Tag;
            ActiveWindow = d;
            if (d == 1)
            {
                item = FileListAdapter.GetItem2(pos);

            }
            else
            {
                item = fileSubListAdapter.GetItem2(pos);
            }
            if (item.Type == FileItemType.Storage &&item.IsDir)
            {
                if (d == 1)
                {
                    RefreshFileList(item.AbsolutePath, FileListAdapter);
                }
                else
                {
                    RefreshFileList(item.AbsolutePath, fileSubListAdapter);
                }
            }else if (item.Type == FileItemType.Zip|| item.Type == FileItemType.Pak)
            {
                if (d == 1)
                {
                    if (item.IsDir == true)
                    {
                        InPakPath =Path.Combine(InPakPath, item.FileName);
                    }else {
                        tip("请长按解压");
                    }
                }
                else
                {
                    if (item.IsDir == true)
                    {
                        InSubPakPath = Path.Combine(InSubPakPath, item.FileName);
                    }else
                    {
                        tip("请长按解压");
                    }
                }
                sendRefreshFileList();
            }
            else if (item.Type == FileItemType.Storage && item.IsDir==false)
            {
                if (item.Extension == ".pak")
                {
                    if (ActiveWindow == 1) { IsInPak = true; lastPath = item.AbsolutePath;  } else { IsSubInPak = true; lastSubPath = item.AbsolutePath; }
                    sendRefreshFileList();
                }
                else if (item.Extension == ".csv" || (item.FileName.StartsWith("BlocksData") && item.FileName.EndsWith("txt")))
                {//进入blocksdata编辑器界面
                    Bundle bundle = new Bundle();
                    bundle.PutString("fullname", item.AbsolutePath);
                    bundle.PutString("name", item.AbsolutePath);
                    Intent intent = new Intent(this, typeof(BlockEditActivity));
                    intent.PutExtra("file", bundle);
                    StartActivity(intent);
                }
                else if (item.Extension == ".dll" || item.Extension == ".exe")
                {
                    sendDialog("反编译功能尚在开发中", "尽情期待");
                }
                else if (item.Extension == ".dae")
                {
                    Bundle bundle = new Bundle();
                    bundle.PutString("fullname", item.AbsolutePath);
                    bundle.PutString("name", item.FileName);
                    Intent intent = new Intent(this, typeof(ModelViewActivity));
                    intent.PutExtra("file", bundle);
                    StartActivity(intent);
                }
                else if (item.Extension == ".zip" || item.Extension == ".scmod" || item.Extension == ".apk")
                {
                    if (ActiveWindow == 1) { IsInPak = true;lastPath = item.AbsolutePath; sendRefreshFileList(); } else { IsSubInPak = true;lastSubPath = item.AbsolutePath; sendRefreshFileList(); }                   
                }
                else if (item.Extension == ".xdb" || item.FileName == "Database.xml")
                {//进入Guid去重界面
                    Bundle bundle = new Bundle();
                    bundle.PutString("fullname", item.AbsolutePath);
                    bundle.PutString("name", item.FileName);
                    Intent intent = new Intent(this, typeof(GuidRepeatAwayActivity));
                    intent.PutExtra("file", bundle);
                    StartActivity(intent);
                }
                else
                {
                    SendTipDialog("不能识别的文件类型");
                }
            }
        }
        public void loadDll(FileInfo file)
        {
            try
            {
                Assembly assembly = Assembly.Load(File.ReadAllBytes(file.FullName));
                sendDialog("解析成功", $"程序集:{assembly.FullName}\n" + (assembly.EntryPoint == null ? string.Empty : "入口:" + assembly.EntryPoint.Name + "[可尝试点击启动]"));
            }
            catch (Exception e)
            {
                sendDialog("错误", "加载程序集失败" + e.ToString());
            }

        }
        public void ExtractZip(ZipArchive zipArchive,string filename,string savePath,bool isdir) {
            foreach (ZipArchiveEntry entry in zipArchive.ReadCentralDir())
            {
                if (entry.FilenameInZip.StartsWith(filename))
                {
                    bool flag = false;
                    if (isdir == false && entry.FilenameInZip == filename) flag = true;
                    string sav = Path.Combine(savePath, isdir ? entry.FilenameInZip : Path.GetFileName(entry.FilenameInZip));
                    string dir = Path.GetDirectoryName(sav);
                    if (Directory.Exists(dir) == false) Directory.CreateDirectory(dir);
                    using (Stream stream = File.OpenWrite(sav))
                    {
                        zipArchive.ExtractFile(entry, stream);
                    }
                    if (flag) break;
                }
            }
        }
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
        {
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            foreach (Permission permission in grantResults)
            {
                if (permission == Permission.Denied) { tip("检测到没有储存读写权限，请检查，否则无法正常使用"); return; }
            }
            RefreshFileList(rootPath, FileListAdapter);
            RefreshFileList(rootPath, fileSubListAdapter);
        }
        public override void OnBackPressed()
        {
            try {
                if ((ActiveWindow == 1 && IsInPak) || (ActiveWindow == 2 && IsSubInPak))
                {
                    if (IsInPak)
                    {
                        string[] spl = InPakPath.Split("/");
                        if (spl.Length == 1)
                        {
                            if (InPakPath == string.Empty)
                            {
                                IsInPak = false;
                                lastPath = Path.GetDirectoryName(lastPath);
                            }
                            else {
                                InPakPath = string.Empty;
                            }
                        }
                        else {
                            InPakPath = InPakPath.Substring(0, InPakPath.Length - spl[spl.Length - 1].Length - 1);
                        }
                        sendRefreshFileList();
                    }else {
                        string[] spl = InSubPakPath.Split("/");
                        if (spl.Length == 1)
                        {
                            if (InSubPakPath == string.Empty)
                            {
                                IsSubInPak = false;
                                lastSubPath = Path.GetDirectoryName(lastSubPath);

                            }
                            else {
                                InSubPakPath = string.Empty;
                            }
                        }
                        else
                        {
                            InSubPakPath = InSubPakPath.Substring(0, InSubPakPath.Length - spl[spl.Length - 1].Length - 1);
                        }
                        sendRefreshFileList();
                    }

                }
                else {
                    string backpath = Path.GetFullPath(@"../", ActiveWindow == 1 ? lastPath : lastSubPath);
                    try
                    {
                        DirectoryInfo directoryInfo = new DirectoryInfo(backpath);
                        directoryInfo.GetDirectories();
                        RefreshFileList(backpath, ActiveWindow == 1 ? FileListAdapter : fileSubListAdapter);
                    }
                    catch
                    {
                        if (IsBackPressed)
                        {
                            System.Environment.Exit(0);
                        }
                        else
                        {
                            tip("再次点击返回退出");
                            IsBackPressed = true;
                            Timer = new Timer(timerCallback, null, 1500, 2000);
                        }
                    }
                }

            }
            catch (Exception e) {
                SendTipDialog(e.Message);
            }
        }
    }
}